import { http_get, http_post, renderView } from "@/utils/request.js"
import vmCommonInit from "./VModel.Common.Extend.js"
import vmExtends from "@/extends/VModel.Extends.js";

function std_name(name) {
  return (name == null || name == "this" || name == "." || name == "~" || name == "$") ? "~" : name;
}

export function onChildVm(parentVm, def, callback) {
  const { ns, name, params } = def;
  const key = vmKey(ns, name);
  let chVm = parentVm.childVms[key];
  if (chVm) {
    chVm.params = params;
    chVm.mode = params.mode || "browse";
    chVm.reLoad();
    callback(chVm);
  } else {
    renderView({ ns, name }, meta => {
      chVm = createVm(parentVm.pageModel);
      initVm(meta, chVm, params);
      chVm.parentVm = parentVm;
      parentVm.childVms[key] = chVm;
      callback(chVm);
    });
  }
}

export function createVm(pageModel) {
  const vm = {
    "pageModel": pageModel,
    "params": {

    },
    "mode": "browse",
    "parentVm": null,
    "childVms": {

    },
    "models": {

    },
    "getModel": (name) => {
      let stdName = std_name(name);
      if (stdName == "~") {
        stdName = vm.models.defaultModel;
      }
      return vm.models[stdName]?.value;
    },
    "getModelRef": (name) => {
      let stdName = std_name(name);
      if (stdName == "~") {
        stdName = vm.models.defaultModel;
      }
      return vm.models[stdName];
    },
    "getData": (name) => {
      return vm.getModel(name)?.data;
    },
    "setData": (name, data) => {
      let stdName = std_name(name);
      if (stdName == "~") {
        stdName = vm.models.defaultModel;
      }
      let model = vm.models[stdName];
      if (model) {
        model.value.exec("setData", data);
      } else {
        console.warn("未找到数据模型：" + stdName);
      }
    },
    "status": {

    },
    "getState": (meta) => {
      const { stateCond } = meta;
      if (stateCond) {
        let callback = vm.status[stateCond];
        if (callback) {
          let data = vm.getData(meta.model);
          return callback({
            meta,
            data
          });
        } else {
          console.warn("定义了状态名称：'" + stateCond + "'但没定义实现！");
          return true;
        }
      } else {
        return true;
      }
    },
    "setState": (name, callback) => {
      vm.status[name] = callback;
    },
    "methods": {
    },
    "events": {

    },
    "beforeEvents": {

    },
    "execute": function (name, args) {
      let callback = vm.events[name];
      if (callback) {
        return callback(args);
      } else {
        return null;
      }
    },
    "setMode": (mode) => {
      vm.mode = mode;
      if (vm.models.$items) {
        vm.models.$items.forEach(x => {
          x.value.mode = mode;
        });
      }
    },
    "on": (name, callback) => {
      vm.events[name] = callback;
    },
    "before": (name, callback) => {
      vm.beforeEvents[name] = callback;
    },
    "execBefore": (name, args) => {
      let callback = vm.beforeEvents[name];
      if (callback) {
        return callback(args);
      } else {
        return true;
      }
    },
    "utils": {
      http_get, http_post,
      dispatch: (name, data, callback) => {
        http_post(name, data, callback);
      },
      "message": (msg) => {
        alert(msg);
      },
      "showDialog": (name, args) => {
        let dialogModel = vm.getModel(name);
        if (dialogModel) {
          dialogModel.args = args;
          dialogModel.exec("setData", args.data.param || {});
          dialogModel.visible = true;
        } else {
          alert("未找到数据模型定义：'" + name + "'")
          args.promise.reject();
        }
      }
    },
    "open": (key, params) => {
      let ns, name;
      if (!key) {
        return false;
      }
      let arrs = key.split(":");
      if (arrs.length == 1) {
        ns = vm.ns;
        name = arrs[0];
      } else if (arrs.length > 1) {
        ns = arrs[0];
        name = arrs[1];
      } else {
        alert("格式错误，" + key);
        return false;
      }
      onChildVm(vm, { ns, name, params }, chVm => {
        chVm.setView();
      });
    },
    "openDetail": (params) => {
      if (!vm.next) {
        alert("未定义明细页属性：'next', 打开失败！\r\n当前视图："
          + vmKey(vm.ns, vm.name));
        return false;
      }
      vm.open(vmKey(vm.ns, vm.next), params);
    },
    "setView": () => {
      if (vm.pageModel) {
        vm.pageModel.value = {
          "key": vm.key,
          "vm": vm
        }
        vm.reLoad();
      }
    },
    "reLoad": () => {
      if (!vm.META) {
        return;
      }
      const { control, onInited } = vm.META;
      if (control == "detail-view") {
        if (vm.mode != "add") {
          vm.execute("detail", {});
        } else {
          vm.execute("add", {});
        }
      } else if (control == "list-view") {
        vm.execute("list", {});
      } else {
        if (onInited) {
          vm.execute(vm.META?.onInited, {});
        }
      }
    },
    "setMethod": (name, handler) => {
      vm.methods[name] = handler;
    },
    "getMethod": (name) => {
      return vm.methods[name];
    }
  }
  return vm;
}

export function initVm(meta, vm, params) {
  vm.META = meta;
  vm.params = params;
  vm.mode = params.mode || vm.mode;
  vm.ns = meta.ns;
  vm.name = meta.name;
  vm.key = vmKey(meta.ns, meta.name);
  vm.next = meta.next;
  vmCommonInit(meta, vm).onInit();
  let ext = meta.vmExtend;
  if (ext != null && ext != "") {
    console.log("load extend files:'" + meta.vmExtendFile + "'");
    let vmExtendfx = vmExtends[ext];
    if (vmExtendfx) {
      const vmExtend = vmExtendfx(meta, vm);
      vmExtend.onInit();
    } else {
      console.warn("未找到扩展对象：" + ext);
    }
  }
  vm.reLoad();
  return vm;
}

export function vmKey(ns, name) {
  return ns + ":" + name;
}

export default {
  createVm, initVm, vmKey
}